package cn.kgc.jdbc.service;

import cn.kgc.jdbc.dao.ClazzDao;
import cn.kgc.jdbc.dao.ClazzDaoImpl;
import cn.kgc.jdbc.dao.StudentDao;
import cn.kgc.jdbc.dao.StudentDaoImpl;
import cn.kgc.jdbc.entity.Clazz;
import cn.kgc.jdbc.entity.Student;
import cn.kgc.jdbc.utils.CodeMsg;
import cn.kgc.jdbc.utils.Result;

import java.util.List;

/**
 * @author: mosin
 * @version: v1.0  2022/8/28
 */
public class StudentService {

    private StudentDao studentDao = new StudentDaoImpl();

    private ClazzDao clazzDao = new ClazzDaoImpl();

    //添加学生
    public Result addStudent(Student student){
        //创建返回结果的实例
        Result result = new Result();
        //将student数据写入数据库 调用持久化层操作
        Integer line = studentDao.insertStudent(student);
        // 根据line 返回对应的结果
        if(line>0){
            result.setCode(CodeMsg.SUCCESS.getCode());
            result.setMsg(CodeMsg.SUCCESS.getMsg());
        }else{
            result.setCode(CodeMsg.ERROR.getCode());
            result.setMsg(CodeMsg.ERROR.getMsg());
        }
        return result;
    }


    // 删除学生信息
    public  Result deleteStudent(Integer id){

        Result result = new Result();
        Integer line = studentDao.deleteById(id);

        // 根据line 返回对应的结果
        if(line>0){
            result.setCode(CodeMsg.SUCCESS.getCode());
            result.setMsg(CodeMsg.SUCCESS.getMsg());
        }else{
            result.setCode(CodeMsg.ERROR.getCode());
            result.setMsg(CodeMsg.ERROR.getMsg());
        }
        return  result;
    }


    // 根据学生的id 班级的名称  分班
    public Result updateStudent(Integer id,String clazzName){

        Result result = new Result();
        // 1.  根据班级的名称 查询班级id
        Clazz clazz = clazzDao.findByClazzName(clazzName);
        long clazzId = clazz.getId();

        // 2.  根据学生的id  修改学生的clazz_id
        Integer line = studentDao.updateStudentById(id,clazzId);

        // 根据line 返回对应的结果
        if(line>0){
            result.setCode(CodeMsg.SUCCESS.getCode());
            result.setMsg(CodeMsg.SUCCESS.getMsg());
        }else{
            result.setCode(CodeMsg.ERROR.getCode());
            result.setMsg(CodeMsg.ERROR.getMsg());
        }

        return  result;
    }


    // 查询所有学生信息
    public  Result findAll(){

        Result result = new Result();
        List<Student> allStudents = studentDao.findAllStudents();
        result.setMsg(CodeMsg.SUCCESS.getMsg());
        result.setCode(CodeMsg.SUCCESS.getCode());
        result.setData(allStudents);
        return result;

    }


}
